package red.mlz.app.controller.sms;

import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import red.mlz.module.module.smslog.entity.SmsLog;
import red.mlz.module.module.smslog.service.SmsLogService;
import red.mlz.module.module.smstask.entity.SmsTask;
import red.mlz.module.module.smstask.service.SmsTaskService;
import red.mlz.module.utils.BaseUtils;
import red.mlz.module.utils.DataUtils;
import red.mlz.module.utils.Response;

import java.util.Arrays;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@RestController
@Slf4j
public class SmsController {

    @Autowired
    private SmsLogService smsLogService;
    @Autowired
    private SmsTaskService smsTaskService;

    //同步发送
    @RequestMapping("/sync-send")
    public Response syncSend(@RequestParam("phone") String phone) {
        if (!DataUtils.isPhoneNumber(phone)) {
            return new Response(4004,"手机号格式错误");
        }
        String code = BaseUtils.getRandNumber(4);

        try {
            SendSmsResponse response = smsLogService.sendSync(phone,"阿里云短信测试",
                    "SMS_154950909", "{\"code\":\""+code+"\"}");

            int timestamp = (int) (System.currentTimeMillis() / 1000);
            SmsLog log = new SmsLog();
            log.setPhone(phone);
            log.setContent("您的验证码：" + code);
            log.setResult(response.getCode() + ":" + response.getMessage());
            log.setSendTime(timestamp);
            log.setCreateTime(timestamp);
            log.setUpdateTime(timestamp);
            log.setIsDeleted(0);
            smsLogService.insert(log);

            return new Response(1001,response.getRequestId());
        } catch (ClientException e) {
            return new Response(4004,e.getMessage());
        }
    }

    //批量发送
    @RequestMapping("/batch-send")
    public Response batchSend(@RequestParam String phone) {

        // 1. 分割手机号并验证格式
        List<String> phones = Arrays.asList(phone.split(","));
        phones.forEach(p -> {
            if (!DataUtils.isPhoneNumber(p)) { // 调用工具类方法验证
                throw new IllegalArgumentException("非法手机号: " + p);
            }
        });

        ExecutorService executor = Executors.newFixedThreadPool(5);

        phones.forEach(p -> {
            executor.submit(() -> {
                String code = BaseUtils.getRandNumber(4);
                int timestamp = 0;
                try {
                    SendSmsResponse response = smsLogService.sendSync(
                            p.toString(),
                            "阿里云短信测试",
                            "SMS_154950909",
                            "{\"code\":\"" + code + "\"}"
                    );
                    timestamp = (int) (System.currentTimeMillis() / 1000);
                    SmsLog Log = new SmsLog();
                    Log.setPhone(p);
                    Log.setContent("您的验证码：" + code);
                    Log.setResult(response.getCode() + ":" + response.getMessage());
                    Log.setSendTime(timestamp);
                    Log.setCreateTime(timestamp);
                    Log.setUpdateTime(timestamp);
                    Log.setIsDeleted(0);
                    smsLogService.insert(Log);
                } catch (ClientException e) {
                    SmsLog log = new SmsLog();
                    log.setPhone(p);
                    log.setContent("您的验证码：" + code);
                    log.setResult("FAIL: " + e.getMessage());
                    log.setSendTime(timestamp);
                    log.setCreateTime(timestamp);
                    log.setUpdateTime(timestamp);
                    log.setIsDeleted(0);
                    smsLogService.insert(log);
                }
            });
        });
        executor.shutdown();
        return new Response(1001,"批量任务已提交");
    }

    //异步发送
    @RequestMapping("/async-send")
    public Response asyncSend(@RequestParam("phone") String phone) {
        String code = BaseUtils.getRandNumber(4);

        SmsTask task = new SmsTask();
        task.setPhone(phone);
        task.setContent(code);
        task.setStatus(0);
        task.setCreateTime((int) (System.currentTimeMillis() / 1000));
        task.setUpdateTime((int) (System.currentTimeMillis() / 1000));
        task.setIsDeleted(0);
        smsTaskService.insert(task);
        return new Response(1001,"任务以提交，ID" + task.getId());
    }

}
